﻿using System;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using InterpriseSuiteEcommerceCommon.DTO;
using InterpriseSuiteEcommerceCommon.Extensions;
using InterpriseSuiteEcommerceCommon.Tool;

namespace InterpriseSuiteEcommerceCommon.InterpriseIntegration
{
    public class MobileWishListPageLiteralRenderer : IShoppingCartHTMLLiteralRenderer
    {
        #region IShoppingCartHTMLLiteralRenderer Members

        public void Render(InterpriseShoppingCart cart, ref StringBuilder output)
        {
            var root = new XElement("FIELDS");
            if (cart.IsEmpty())
            {
                if (cart.CartType == CartTypeEnum.WishCart)
                {
                    var t1 = new Topic("MobileEmptyWishListText", cart.ThisCustomer.LocaleSetting, cart.SkinID, null);
                    root.Add(new XElement("MOBILEEMPTYWISHLISTTEXT", t1.Contents));    
                }
            }
            else
            {
                bool showPicsInCart = AppLogic.AppConfigBool("ShowPicsInCart");
                bool showLinkBack = AppLogic.AppConfigBool("LinkToProductPageInCart");
                bool hideUnitMeasure = AppLogic.AppConfigBool("HideUnitMeasure");

                root.Add(new XElement("WISHLIST_HEADER_TEXT", AppLogic.GetString("mobile.wishlist.aspx.1", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
                foreach (CartItem cartItem in cart.CartItems)
                {
                    var xmlcartItem = new XElement("CART_ITEMS");
                    xmlcartItem.Add(new XElement("CART_ITEM_ID", cartItem.m_ShoppingCartRecordID));
                    root.Add(xmlcartItem);

                    string productLinkHref = InterpriseHelper.MakeItemLink(cartItem.ItemCode);
                    if (showPicsInCart)
                    {
                        xmlcartItem.Add(new XElement("SHOWPICSINCART", true));
                        if (showLinkBack) { xmlcartItem.Add(new XElement("LinkBack", productLinkHref)); }

                        var img = ProductImage.Locate("product", cartItem.ItemCounter, "icon");
                        if (null != img) { xmlcartItem.Add(new XElement("ProductImagePath", img.src)); }
                    }

                    // Line Item
                    switch (cartItem.ItemType)
                    {
                        case Interprise.Framework.Base.Shared.Const.ITEM_TYPE_MATRIX_GROUP:

                        #region "ITEM_TYPE_MATRIX_ITEM"

                        case Interprise.Framework.Base.Shared.Const.ITEM_TYPE_MATRIX_ITEM:
                            
                            if (showLinkBack)
                            {
                                xmlcartItem.Add(new XElement("ProductLinkHref", productLinkHref));
                            }
                            xmlcartItem.Add(new XElement("ProductLinkName", Security.HtmlEncode(cartItem.DisplayName)));

                            var matrixDetails = new StringBuilder();
                            // display the details
                            using (var con = DB.NewSqlConnection())
                            {
                                con.Open();

                                string query = string.Format("exec eCommerceGetMatrixItemAttributes @ItemCode = NULL, @MatrixItemCode = {0}, @WebsiteCode = {1}, @CurrentDate = {2}, @LanguageCode = {3}, @ContactCode = {4}", 
                                                                    DB.SQuote(cartItem.ItemCode), 
                                                                    DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode), 
                                                                    DB.SQuote(Localization.DateTimeStringForDB(DateTime.Now)), 
                                                                    DB.SQuote(Customer.Current.LanguageCode), 
                                                                    DB.SQuote(Customer.Current.ContactCode));

                                using (var reader = DB.GetRSFormat(con, query))
                                {
                                    if (reader.Read())
                                    {
                                        for (int ctr = 1; ctr <= 6; ctr++)
                                        {
                                            string attribute = DB.RSField(reader, string.Format("Attribute{0}", ctr));
                                            string attributeValue = DB.RSField(reader, string.Format("Attribute{0}ValueDescription", ctr));

                                            if (string.IsNullOrEmpty(attribute) && string.IsNullOrEmpty(attributeValue)) continue;
                                            matrixDetails.AppendFormat("&nbsp;&nbsp;{0}:{1}<br />", Security.HtmlEncode(attribute), Security.HtmlEncode(attributeValue));
                                        }
                                    }
                                }
                            }
                            xmlcartItem.Add(new XElement("MatrixDetails", matrixDetails.ToString()));
                            break;

                        #endregion

                        #region "ITEM_TYPE_KIT"

                        case Interprise.Framework.Base.Shared.Const.ITEM_TYPE_KIT:
                            
                            if (showLinkBack)
                            {
                                xmlcartItem.Add(new XElement("ProductLinkHref", productLinkHref));
                            }
                            xmlcartItem.Add(new XElement("ProductLinkName", Security.HtmlEncode(cartItem.DisplayName)));

                            bool isCurrencyIncludedForInventorySelling = InterpriseHelper.IsCurrencyIncludedForInventorySelling(cart.ThisCustomer.CurrencyCode);

                            // Special case 2 
                            //  Currency is added in Inventory Selling Currency late
                            //  after the kit has been created, ideally the kit should regenerate kit pricing for this currency
                            //  but for the meantime, we should handle this by looking into the home currency
                            bool currencyIsIncludedInInventorySellingCurrencyButHasNoKitPricingDetailYetForThisItem =
                            InterpriseHelper.CurrencyIsIncludedInInventorySellingCurrencyButHasNoKitPricingDetailYet(cart.ThisCustomer.CurrencyCode, cartItem.ItemCode);

                            var kitItems = new XElement("KIT_ITEMS");
                            kitItems.Add(new XElement("KIT_SHOWDETAILSTEXT", AppLogic.GetString("mobile.wishlist.aspx.2", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
                            kitItems.Add(new XElement("KIT_HIDEDETAILSTEXT", AppLogic.GetString("mobile.wishlist.aspx.3", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
                            // read the records from the EcommerceKitCart table...

                            var lstKitDetails = AppLogic.GetKitDetail(cartItem.ItemCode,
                                                                      CommonLogic.IIF((isCurrencyIncludedForInventorySelling && !currencyIsIncludedInInventorySellingCurrencyButHasNoKitPricingDetailYetForThisItem), cart.ThisCustomer.CurrencyCode, Currency.GetHomeCurrency()),
                                                                      cart.ThisCustomer.LocaleSetting,
                                                                      cart.ThisCustomer.CustomerCode,
                                                                      cartItem.Id, 
                                                                      cart.ThisCustomer.ContactCode);

                            lstKitDetails.ForEach(item => {
                                kitItems.Add(new XElement("KITITEM", Security.HtmlEncode(string.Format("({0}) {1}", Localization.ParseLocaleDecimal(item.Quantity, cart.ThisCustomer.LocaleSetting).TryParseInt().Value, Security.HtmlEncode(item.Name)))));
                            });

                            xmlcartItem.Add(kitItems);
                            break;

                        #endregion

                        #region "Stock"

                        default:
                            if (showLinkBack)
                            {
                                xmlcartItem.Add(new XElement("ProductLinkHref", productLinkHref));
                            }
                            xmlcartItem.Add(new XElement("ProductLinkName", Security.HtmlEncode(cartItem.DisplayName)));
                            break;

                        #endregion
                    }

                    /*************** multiple address **********************/
                    if (cart.HasMultipleShippingAddresses() && !cartItem.IsDownload && !cartItem.IsService)
                    {
                        output.Append(AppLogic.GetString("shoppingcart.cs.24", cart.SkinID, cart.ThisCustomer.LocaleSetting));
                        output.Append(" ");

                        var adr = new Address();
                        bool includename = true;

                        if (cartItem.m_ShippingAddressID == cart.ThisCustomer.PrimaryShippingAddressID)
                        {
                            adr.LoadByCustomer(cart.ThisCustomer, AddressTypes.Shipping, cartItem.m_ShippingAddressID);
                            output.Append(AppLogic.GetString("account.aspx.10", cart.SkinID, cart.ThisCustomer.LocaleSetting));
                        }
                        else if (cartItem.m_ShippingAddressID == cart.ThisCustomer.PrimaryBillingAddressID)
                        {
                            adr.LoadByCustomer(cart.ThisCustomer, AddressTypes.Billing, cartItem.m_ShippingAddressID);
                            output.Append(AppLogic.GetString("account.aspx.8", cart.SkinID, cart.ThisCustomer.LocaleSetting));
                        }
                        else
                        {
                            output.Append(adr.Name);
                            includename = false;
                        }

                        output.Append("<div style=\"margin-left: 10px;\">");
                        output.Append(adr.DisplayString(false, false, includename, "<br>"));
                        output.Append("</div>");

                        output.Append("<div>");
                        output.Append(AppLogic.GetString("order.cs.23", cart.SkinID, cart.ThisCustomer.LocaleSetting));
                        output.Append(cartItem.m_ShippingMethod);
                        output.Append("</div>");
                    }

                    if (!hideUnitMeasure)
                    {
                        xmlcartItem.Add(new XElement("NOT_HIDE_UNIT_MEASURE", true));
                        var availableUnitMeasures = AppLogic.GetAvailableUnitMesure(cart.ThisCustomer.CustomerCode, cartItem.ItemCode, AppLogic.AppConfigBool("ShowInventoryFromAllWarehouses"), cart.ThisCustomer.IsNotRegistered);
                        if (availableUnitMeasures.Count > 1)
                        {
                            xmlcartItem.Add(new XElement("AVAILABLEUNITMESSURE_GREATER_ONE", true));
                            xmlcartItem.Add(new XElement("MULTIPLE_UNITMEASURECODENAME", "UnitMeasureCode_{0}".FormatWith(cartItem.m_ShoppingCartRecordID)));
                            xmlcartItem.Add(new XElement("MULTIPLE_UNITMEASURECODEID", "UnitMeasureCode_{0}".FormatWith(cartItem.m_ShoppingCartRecordID)));

                            foreach (var unitMeasureValue in availableUnitMeasures)
                            {
                                var unitmeasures = new XElement("UNITMEASSURE_ITEM");
                                xmlcartItem.Add(unitmeasures);
                                bool isCurrentUnitMeasureTheOneSelectedInProductPage = cartItem.UnitMeasureCode.Equals(unitMeasureValue.Key, StringComparison.InvariantCultureIgnoreCase);
                                unitmeasures.Add(new XElement("VALUE", unitMeasureValue.Key.ToHtmlEncode()));
                                unitmeasures.Add(new XElement("TEXT", unitMeasureValue.Value));
                                unitmeasures.Add(new XElement("SELECTED", isCurrentUnitMeasureTheOneSelectedInProductPage));
                            }
                        }
                        else
                        {
                            xmlcartItem.Add(new XElement("AVAILABLEUNITMESSURE_GREATER_ONE", false));
                            xmlcartItem.Add(new XElement("UNITMEASURECODEID", "UnitMeasureCode_{0}".FormatWith(cartItem.m_ShoppingCartRecordID)));
                            xmlcartItem.Add(new XElement("UNITMEASURECODENAME", "UnitMeasureCode_{0}".FormatWith(cartItem.m_ShoppingCartRecordID)));
                            xmlcartItem.Add(new XElement("UNITMEASURECODEVALUE", cartItem.UnitMeasureCode.ToHtmlEncode()));
                            xmlcartItem.Add(new XElement("UNITMEASURECODESPANDISPLAY", availableUnitMeasures[0].Value.ToHtmlEncode()));
                        }
                    }

                    xmlcartItem.Add(new XElement("ISRESTRICTEDQUANTITIES", (cartItem.RestrictedQuantities.Count > 0)));
                    if (cartItem.RestrictedQuantities.Count > 0)
                    {
                        xmlcartItem.Add(cartItem.RestrictedQuantities
                                .Select(r => new XElement("RESTRICTEDQUANTITIES",
                                    new XElement("QTY", r),
                                    new XElement("SELECTED", r == cartItem.m_Quantity))));
                    }
                    else
                    {
                        xmlcartItem.Add(new XElement("INPUTQUANTITYVALUE", Localization.ParseLocaleDecimal(cartItem.m_Quantity, cart.ThisCustomer.LocaleSetting)));
                    }

                    if (AppLogic.AppConfigBool("ShowCartDeleteItemButton"))
                    {
                        xmlcartItem.Add(new XElement("SHOWCARTDELETEITEMBUTTON", true));
                        string deleteCaption = AppLogic.GetString("shoppingcart.cs.31", cart.SkinID, cart.ThisCustomer.LocaleSetting);
                        deleteCaption = string.IsNullOrEmpty(deleteCaption) ? "Delete" : deleteCaption;
                        xmlcartItem.Add(new XElement("DELETECAPTION", deleteCaption));
                        //xmlcartItem.Add(new XElement("ONCLICK", "DeleteWishListItem('{0}');".FormatWith(cartItem.m_ShoppingCartRecordID)));
                    }

                    //this.form.Quantity_{0}.value='0'

                    xmlcartItem.Add(new XElement("MINORDERQUANTITYID", cartItem.m_ShoppingCartRecordID));
                    xmlcartItem.Add(new XElement("MINORDERQUANTITYNAME", cartItem.m_ShoppingCartRecordID));
                    xmlcartItem.Add(new XElement("MINORDERQUANTITYVALUE", cartItem.m_MinimumQuantity));

                    if (AppLogic.ItemHasVisibleBuyButton(cartItem.ItemCode))
                    {
                        xmlcartItem.Add(new XElement("SHOWMOVETOCARTBUTTON", true));
                        xmlcartItem.Add(new XElement("SHOWMOVETOCARTBUTTONVALUE", String.Format(AppLogic.GetString("shoppingcart.cs.3", cart.SkinID, cart.ThisCustomer.LocaleSetting), AppLogic.GetString("AppConfig.CartPrompt", cart.SkinID, cart.ThisCustomer.LocaleSetting))));
                    }
                } //cart else
            }

            string html = new XmlPackage2("page.wishlist_template.xml.config", root).TransformString();
            output.Append(html);
        }

        #endregion
    }
}
